package com.itheima.d07_modifiy_question;

import com.itheima.d06_set_treeset.Student;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * 目标：了解集合并发修改问题和解决方案
 */
public class Test {

    public static void main(String[] args) {
        //1.创建集合，存储学生信息
        ArrayList<Student> students = new ArrayList<>();

        //2.添加学生信息`
        students.add(new Student("狗哥", 18, 99.5));
        students.add(new Student("厂长", 19, 90));
        students.add(new Student("水子哥", 17, 80));
        students.add(new Student("圣枪哥", 18, 99.8));

        //3.打印结果
        //迭代器遍历机制：遍历集合的过程中，不允许增删元素，否则报并发修改异常
        Iterator<Student> iterator = students.iterator();

        while(iterator.hasNext()){
            Student stu = iterator.next();
            if(stu.getName().equals("厂长")){
                //4.解决方案：使用迭代器提供删除方法进行删除操作
                //students.remove(stu);
                iterator.remove(); //迭代器指向谁就删除谁
            }
            //students.add(new Student("小叮当", 18, 99.5));
        }


        //4.删除完毕后，在打印
        System.out.println("===============");
        students.forEach(System.out::println);


        System.out.println("================");
        //5.删除名称中包含哥的学生
        for (int i = 0; i < students.size(); i++) {
            Student stu = students.get(i);

            if(stu.getName().contains("哥")){
                students.remove(stu);
                //i--;
            }
        }
        System.out.println("================");
        students.forEach(System.out::println);

    }
}
